package com.liuxin.mycontactdemo.activity;


import android.Manifest;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


import com.liuxin.mycontactdemo.R;
import com.liuxin.mycontactdemo.adapter.ExportAdapter;
import com.liuxin.mycontactdemo.provider.ContactProvider;
import com.liuxin.mycontactdemo.untils.ThreadUtils;
import com.liuxin.mycontactdemo.untils.ToastUtils;
import com.liuxin.mycontactdemo.vo.Contact;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ExportContactActivity extends AppCompatActivity {

    @InjectView(R.id.exportLv)
    ListView exportListView;
    private List<Contact> contactList=new ArrayList<>();
    private ExportAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export_contact);
        ButterKnife.inject(this);
        registerForContextMenu(exportListView);
        initData();
        initListData();
    }
    private void initListData() {
        Cursor cursor = getContentResolver().query(ContactProvider.URI_CONTACT,null,null,null,null);
        if(cursor.getCount() > 0){
            while(cursor.moveToNext()){
                contactList.add(new Contact(cursor.getString(1),cursor.getString(2),cursor.getString(3),false));
            }
        }
    }

    private void initView() {
        ThreadUtils.runInUIThread((new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
            }
        }));
    }
    private void initData() {
        //权限申请
        if(ContextCompat.checkSelfPermission(ExportContactActivity.this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(ExportContactActivity.this,new String[]{Manifest.permission.WRITE_CONTACTS},1);
        }else {
            exportContact();
        }

    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("导出联系人");
        menu.add(0, Menu.FIRST,0,"全选");
        menu.add(0, Menu.FIRST + 1,1,"全不选");
        menu.add(0, Menu.FIRST + 2,2,"导出");
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()){
            case Menu.FIRST:
                selectAll();
                break;
            case Menu.FIRST + 1:
                unSelectAll();
                break;
            case Menu.FIRST + 2:
                writeContactAndriod();
                finish();
        }
        return super.onContextItemSelected(item);
    }

    /**
     * 导入手机
     */
    private void writeContactAndriod() {
        ThreadUtils.runInThread(new Runnable() {
            @Override
            public void run() {
                int count = 0;
                for (Contact contact : contactList){
                    if(contact.isChecked()){
                        ContentValues contentValues = new ContentValues();
                        Uri uri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI,contentValues);
                        long rawContactId = ContentUris.parseId(uri);
                        contentValues.clear();

                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
                        // 内容类型
                        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                        // 联系人名字
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,contact.getName());
                        // 向联系人URI添加联系人名字
                        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
                        contentValues.clear();

                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
                        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        // 联系人的电话号码
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.getPhone());
                        // 电话类型
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                        // 向联系人电话号码URI添加电话号码
                        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
                        contentValues.clear();

                        contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
                        contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
                        // 联系人的Email地址
                        contentValues.put(ContactsContract.CommonDataKinds.Email.DATA,contact.getEmail());
                        // 电子邮件的类型
                        contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK);
                        // 向联系人Email URI添加Email数据
                        getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
                        count++;
                    }
                }
                ToastUtils.showToastSafe(ExportContactActivity.this,"已导出" + count + "联系人！");

            }
        });
    }

    /**
     * 全不选
     */
    private void unSelectAll() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                for (Contact contact : contactList){
                    contact.setChecked(false);
                }
                initView();
            }
        });
    }

    /**
     * 全选
     */
    private void selectAll() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                for (Contact contact : contactList){
                    contact.setChecked(true);
                }
                initView();
            }
        });
    }

    private void exportContact() {
        ThreadUtils.runInUIThread(new Runnable() {
            @Override
            public void run() {
                adapter = new ExportAdapter(ExportContactActivity.this,contactList);
                exportListView.setAdapter(adapter);
            }
        });
    }
}